/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: 北京银杉金服科技有限公司
 * 系统版本: 1.0.0
 * 开发人员: zhangfb
 * 开发时间: 2018/9/10 15:29
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.hyacinth.seckill.repository;

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
 * 自定义工厂
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public class CustomerJpaRepositoryFactoryBean<T extends Repository<S, ID>, S extends Serializable, ID extends Serializable>
        extends JpaRepositoryFactoryBean<T, S, ID> {

    public CustomerJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        return new CustomerRepositoryFactory(entityManager);
    }

    //创建一个内部类，该类不用在外部访问
    private static class CustomerRepositoryFactory<T extends Serializable, ID extends Serializable> extends JpaRepositoryFactory {

        private EntityManager entityManager;

        CustomerRepositoryFactory(EntityManager entityManager) {
            super(entityManager);
            this.entityManager = entityManager;
        }

        //设置具体的实现类是BaseRepositoryImpl
        @Override
        protected SimpleJpaRepository<?, ?> getTargetRepository(RepositoryInformation information, EntityManager entityManager) {
            JpaEntityInformation<?, ?> entityInformation = getEntityInformation(information.getDomainType());
            return new BaseRepositoryImpl<>((JpaEntityInformation<T, ID>) entityInformation, entityManager);
        }

        //设置具体的实现类的class
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
            return BaseRepositoryImpl.class;
        }
    }
}
